<template>
  <div class="review-stats">

    <div class="flex-container">
      <!-- 左侧柱形图 -->
      <div id="chart" class="chart-box"></div>

      <!-- 右侧单词列表 -->
      <div v-if="selectedWords.length" class="word-list">
        <h3 style="color: #dadfe6;">单词列表（最多显示前 15 个）</h3>
        <ul>
          <li v-for="word in selectedWords.slice(0, 15)" :key="word.id">
            {{ word.word }} - 遗忘率: {{ word.rate }}
          </li>
        </ul>
      </div>
    </div>




<!--    <el-pagination-->
<!--        style="margin-top: 20px; text-align: right;"-->
<!--        background-->
<!--        layout="prev, pager, next"-->
<!--        :total="pagination.total"-->
<!--        :page-size="pagination.per_page"-->
<!--        :current-page.sync="pagination.current"-->
<!--        @current-change="fetchData"-->
<!--    />-->

    <div class="hotspot-container">
      <div ref="heatmapChart" style="width: 100%; height: 900px;"></div>

      <div v-if="selectedCell" class="detail-panel">
        <h3>{{ selectedCell.title }}</h3>
        <p>平均遗忘率: <strong>{{ (selectedCell.avg_rate * 100).toFixed(1) }}%</strong></p>
        <p>单词总数: {{ selectedCell.word_count }}</p>
        <p>高频遗忘词: {{ selectedCell.hard_word_count }}</p>
      </div>
    </div>


  </div>
</template>

<script>
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'BaseBarChart',
  data() {
    return {
      reviews: [],
      pagination: {
        total: 0,
        per_page: 20,
        current: 1,
      },
      rateData: [],
      bookCountData: {},
      heatData: [],
      xLabels: [],
      yLabels: [],
      chart: null,
      selectedWords: [],
      selectedCell: null,
    }
  },
  mounted() {
    // this.fetchData()
    this.$nextTick(() => {
      this.fetchHeatData()
      this.fetchHistoryData()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      if (this.chart) this.chart.resize()
    },
    async fetchWordsByRange(low, high) {
      const res = await axios.get('/api/word/words_by_range', {
        params: {low, high}
      })
      this.selectedWords = res.data
    },

    async fetchHistoryData() {
      const res = await axios.get('/api/word/forget_rate_distribution')
      const dist = res.data.distribution
      const avg = res.data.avg_rate

      const xAxis = dist.map(d => d.range)
      const barData = dist.map(d => d.count)

      this.initChart(xAxis, barData, avg)
    },

    async fetchHeatData() {
      try {
        const res = await axios.get('/api/word/hotspot_matrix');
        console.log('Heatmap raw data:', res.data);

        // 移除了未使用的 max_hard 解构
        const { x_labels, y_labels, data } = res.data;

        // 1. 基础热力图数据
        const heatmapData = data.map(item => [item.x, item.y, item.value || 0]);

        // 2. 完整数据用于交互
        const fullData = data.map(item => ({
          ...item,
          value: parseFloat(item.value) || 0,
          hard: parseInt(item.hard) || 0
        }));

        // 初始化图表
        this.heatmapChart = echarts.init(this.$refs.heatmapChart);

        const option = {
          title: {
            text: '单词遗忘热点矩阵',
            subtext: '颜色深浅表示遗忘率高低',
            textStyle: { color: '#fff' }
          },
          tooltip: {
            position: 'top',
            formatter: params => {
              const d = fullData[params.dataIndex];
              return `
            <strong>List ${y_labels[d.y]} - Index ${x_labels[d.x]}</strong><br/>
            平均遗忘率: ${(d.value * 100).toFixed(1)}%<br/>
            单词总数: ${d.count || 0}<br/>
            高频遗忘词: ${d.hard}
          `;
            }
          },
          grid: {
            top: '15%',
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: x_labels,
            splitArea: { show: true },
            axisLabel: {
              color: '#fff',
              rotate: 45 // 如果标签太长可以旋转
            }
          },
          yAxis: {
            type: 'category',
            data: y_labels,
            splitArea: { show: true },
            axisLabel: { color: '#fff' }
          },
          visualMap: {
            min: 0,
            max: 1,
            calculable: true,
            orient: 'horizontal',
            left: 'center',
            bottom: '5%',
            inRange: {
              color: ['#B71C1C', '#0288D1', '#81D4FA', '#FFD54F', '#C8E6C9', '#66BB6A']
            },
            outOfRange: {
              color: ['#FF5722', '#FFCDD2']
            },
            textStyle: { color: '#fff' },
            text: ['低遗忘率', '高遗忘率']
          },
          series: [{
            name: '遗忘率',
            type: 'heatmap',
            data: heatmapData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            // 渐进渲染提升性能
            progressive: 1000,
            animation: false
          }

          ]
        };

        this.heatmapChart.setOption(option);

        // 点击事件
        this.heatmapChart.on('click', params => {
          const d = fullData[params.dataIndex];
          this.selectedCell = {
            title: `List ${y_labels[d.y]} - Index ${x_labels[d.x]}`,
            avg_rate: d.value,
            word_count: d.count,
            hard_word_count: d.hard
          };
        });

        // 窗口缩放时重绘
        window.addEventListener('resize', () => this.heatmapChart.resize());

      } catch (error) {
        console.error('加载热力图数据失败:', error);
      }
    },


    initChart(xAxis, barData, avgRate) {
      const option = {
        title: {
          text: '单词遗忘率分布',
          textStyle: {color: '#fff'}
        },
        tooltip: {},
        xAxis: {
          data: xAxis,
          axisLabel: {color: '#fff'}
        },
        yAxis: {axisLabel: {color: '#fff'}},
        series: [
          {
            name: '单词数量',
            type: 'bar',
            data: barData
          },
          {
            name: '平均遗忘率参考线',
            type: 'line',
            data: new Array(xAxis.length).fill(avgRate * 100), // 折线Y值为平均率*100
            lineStyle: {type: 'dashed'},
            markLine: {
              silent: true,
              data: [{yAxis: avgRate * 100}],
              lineStyle: {color: '#a5c9f6'}
            }
          }
        ]
      }

      this.barChart = echarts.init(document.getElementById('chart'))
      this.barChart.setOption(option)

      // 添加点击事件
      this.barChart.on('click', params => {
        const range = params.name.split('-')
        const low = parseFloat(range[0])
        const high = parseFloat(range[1])
        this.fetchWordsByRange(low, high)
      })
    },
  }
}
</script>

<style >

.hotspot-container {
  width: 70%;
  height: auto;
  position: relative;
  display: flex;
  flex-wrap: wrap;
}

.hotspot-container > div {
  flex: 1;
  min-width: 300px; /* 或者加上最大宽度控制 */
}


.detail-panel {
  margin-top: 10px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}
.review-stats {
  padding: 10px;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  gap: 20px;
}

.chart-box {
  flex: 1;
  max-width: 70%;
  height: 40vh; /* 相对高度 */
}

.word-list {
  flex: 0 0 300px;
  max-width: 30%;
  color: #c1d0d8;
}

.word-list h3 {
  color: #dadfe6;
}

.hotspot-container {
  margin-top: 0px;
}

.hotspot-container > div:first-child {
  width: 80%;
  height: 60vh;  /* 相对视口高度 */
  min-height: 300px;
}

.detail-panel {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

</style>




